package org.jupiter.blog.service.service.impl;

import org.jupiter.blog.api.convertor.JupiterRoleStructConvertor;
import org.jupiter.blog.api.domain.JupiterRole;
import org.jupiter.blog.api.dto.JupiterRoleDTO;
import org.jupiter.blog.service.mapper.JupiterRoleMapper;
import org.jupiter.blog.service.service.JupiterRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class JupiterRoleServiceImpl implements JupiterRoleService {

	@Autowired
	private JupiterRoleMapper roleMapper;

	@Autowired
	private JupiterRoleStructConvertor roleConvertor;

	@Override
	@Transactional
	public void createRole(JupiterRoleDTO dto) {
		JupiterRole role = roleConvertor.toEntity(dto);
		if (!StringUtils.hasText(role.getUuid())){
			role.setUuid(UUID.randomUUID().toString());
		}
		role.setCreateTime(LocalDateTime.now());
		role.setUpdateTime(LocalDateTime.now());
		roleMapper.insert(role);
	}

	@Override
	@Transactional(readOnly = true)
	public JupiterRoleDTO getById(String uuid) {
		JupiterRole role = roleMapper.selectByUuid(uuid);
		return roleConvertor.toDto(role);
	}

	@Override
	@Transactional
	public void updateRole(String uuid, JupiterRoleDTO dto) {
		JupiterRole role = roleConvertor.toEntity(dto);
		role.setUuid(uuid);
		role.setUpdateTime(LocalDateTime.now());
		roleMapper.updateByUuidSelective(role);
	}

	@Override
	@Transactional
	public void deleteRole(String uuid) {
		roleMapper.deleteByUuid(uuid);
	}

	@Override
	@Transactional(readOnly = true)
	public List<JupiterRoleDTO> getByPage(JupiterRoleDTO queryDTO) {
		int offset = (queryDTO.getPage() - 1) * queryDTO.getSize();
		List<JupiterRole> roles = roleMapper.selectByPage(
				queryDTO.getName(),
				offset,
				queryDTO.getSize()
		);
		return roleConvertor.toDtoList(roles);
	}

	@Override
	@Transactional(readOnly = true)
	public long getCount(JupiterRoleDTO queryDTO) {
		return roleMapper.countByQuery(queryDTO.getName());
	}

	@Override
	@Transactional(readOnly = true)
	public List<JupiterRoleDTO> getAll() {
		List<JupiterRole> roles = roleMapper.selectAll();
		return roleConvertor.toDtoList(roles);
	}

	@Override
	@Transactional(readOnly = true)
	public List<JupiterRoleDTO> getByUserId(String userId) {
		List<JupiterRole> roles = roleMapper.selectByUserId(userId);
		return roleConvertor.toDtoList(roles);
	}

	@Override
	public void restoreRole(String uuid) {
		roleMapper.restoreRole(uuid);
	}

}
